import { Provide, Inject } from '@midwayjs/decorator';
import { JwtService } from '@midwayjs/jwt';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '../entity/user.entity';
import { PasswordDiffer, UserExists } from '../error/custom.error';
import { md5 } from '../utils';

@Provide()
export class UserService {
  @Inject()
  jwt: JwtService;

  @Inject()
  ctx: Context;

  @InjectEntityModel(UserEntity)
  userModal: Repository<UserEntity>;

  // 生成Token
  async generateToken(username: string) {
    return await this.jwt.sign({
      username,
      confuse: `${+new Date()}|${Math.random()}`,
    });
  }

  // 执行用户相关SQL语句
  async queryUserBySQL(sql: string) {
    return await this.userModal.query(sql);
  }

  // 从数据库中寻找用户
  async findUser(
    username: string,
    existCallback?: (t?: UserEntity) => void,
    notExistCallBack?: () => void
  ) {
    const res = await this.userModal.findOne({
      where: { username },
      relations: ['messages'],
    });
    // 如果存在执行成功回调
    res && existCallback && existCallback(res);
    // 如果不存在执行失败回调
    !res && notExistCallBack && notExistCallBack();
    return res;
  }

  // 添加用户
  async addUser(username: string, password: string, confirmPassword: string) {
    // 判断两次密码输入是否相同
    if (password !== confirmPassword) {
      throw new PasswordDiffer();
    }
    // 查询是否已经有用户名存在
    await this.findUser(username, () => {
      throw new UserExists();
    });
    // 注册成功
    const newUser = new UserEntity(username, md5(password));
    await this.userModal.save(newUser);
  }

  // 修改用户数据
  async changeUser(target: UserEntity, keyVal: Partial<UserEntity>) {
    this.userModal.save({ ...target, ...keyVal });
  }

  // 删除用户
  async deleteUser(username: string) {
    this.userModal.delete({ username });
  }
}
